package com.dyw.ycgovfinance.mvp.open;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.dyw.ycgovfinance.R;
import com.dyw.ycgovfinance.adapter.ViewPagerAdapterOpenNewsYsJs;
import com.dyw.ycgovfinance.adapter.list.ListAdapterForOpenNews;
import com.dyw.ycgovfinance.app.CustomApplication;
import com.dyw.ycgovfinance.bean.NewsKindBean;
import com.dyw.ycgovfinance.bean.NewsListBean;
import com.dyw.ycgovfinance.commom.Config;
import com.dyw.ycgovfinance.commom.IntentKey;
import com.dyw.ycgovfinance.mvp.base.BaseFragment;
import com.dyw.ycgovfinance.mvp.info.FragmentInfoHome;
import com.dyw.ycgovfinance.mvp.news.newsdetail.ActivityNewsDetail;
import com.dyw.ycgovfinance.mvp.open.newslist.ActivityOpenNewsList;
import com.dyw.ycgovfinance.util.CommonUtil;
import com.dyw.ycgovfinance.util.DensityUtil;
import com.dyw.ycgovfinance.util.LogUtil;
import com.dyw.ycgovfinance.util.ToastUtil;
import com.dyw.ycgovfinance.util.schedulers.SchedulerProvider;
import com.dyw.ycgovfinance.widget.ListViewForScrollView;
import com.google.gson.reflect.TypeToken;
import com.jakewharton.rxbinding.view.RxView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import rx.functions.Action1;

/**
 * Created by clboys on 2017/6/28.
 */

public class FragmentOpenMainView extends BaseFragment implements OpenMainContract.View{


    //默认的是isFirstVisibles true ,刚进来的时候分两种情况
    //1.如果切过来的时候 setVisibleHint在OnCreate之前调用，那isFirstVisible为true，这个时候不进行任何操作；
    //等方法执行到onActivityCreated的时候，在执行一次setUserVisibleHint 这个时候把默认的是isFirstVisibles 设为false
    //然后这个时候调用setUserVISIBLEhINT为true  去获取数据
    //2.如果是后面再次切过来，那isFirstVisible已经为false，那就可以直接通过setUserVisibleHint获取数据了

    //代表这个界面是不是第一次被使用
    boolean isFirstUsed = true;
    boolean isGetData = false;

    OpenMainContract.Presenter mPresenter;

    List<NewsKindBean> mCommonNewsKind = new ArrayList<>();


    NewsKindBean  mGovJsNewsKind ;
    NewsKindBean  mGovYsNewsKind ;

    NewsKindBean mNowChooseGovNewsKind;

    NewsKindBean  mDepartJsNewsKind ;
    NewsKindBean  mDepartYsNewsKind ;

    NewsKindBean mNowChooseDepartNewsKind;

    List<NewsListBean> mGongShiGongGaoNewsList = new ArrayList<>();
    List<NewsListBean> mPolicyFileNewsList = new ArrayList<>();
    List<NewsListBean> mGovYsNewsList = new ArrayList<>();
    List<NewsListBean> mGovJsNewsList = new ArrayList<>();
    List<NewsListBean> mDepartYsNewsList = new ArrayList<>();
    List<NewsListBean> mDepartJsNewsList = new ArrayList<>();

    private static final String DEFAULT_PAGE_INDEX_STR = "1";
    private static final String DEFAULT_PAGE_PASIZE_STR= "5";

    private TextView tvGsggMore;
    private ListViewForScrollView lvGsgg;
    private TextView tvZcwjMore;
    private ListViewForScrollView lvZfwj;
    private RadioGroup rgGovYsjs;
    private RadioButton rbGovYs;
    private RadioButton rbGovJs;
    private TextView tvGovYsjsMore;
    private ViewPager vpGovYsjs;
    private RadioGroup rgDepartYsjs;
    private RadioButton rbDepartYs;
    private RadioButton rbDepartJs;
    private TextView tvDepartYsjsMore;
    private ViewPager vpDepartYsjs;


    ListAdapterForOpenNews mGsggNewsAdapter;
    ListAdapterForOpenNews mZcwjNewsAdapter;
    ViewPagerAdapterOpenNewsYsJs mGovYsJsNewsVpAdapter;
    ViewPagerAdapterOpenNewsYsJs mDepartYsJsNewsVpAdapter;



    List<List<NewsListBean>> mGovYsJsNewsData = new ArrayList<>();
    List<List<NewsListBean>> mDepartYsJsNewsData = new ArrayList<>();





    public static FragmentOpenMainView newInstance() {
        FragmentOpenMainView fragment = new FragmentOpenMainView();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPresenter = new OpenMainPresenter(this, SchedulerProvider.getInstance(), CustomApplication.getInstance().getHttpService());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_open_view, container, false);
        assignView(view);
        initView();

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //fragment 可见的情况下 进行加载数据。不可见则不加载
        if (getUserVisibleHint() == true) {
            if (isFirstUsed == true) {
                isFirstUsed = false;
                setUserVisibleHint(true);
            }
            //不可见，说明fragment已经初始话完成,就直接把isFirstVisible改为false 再次切过来的时候就直接可以加载数据了
        } else {
            isFirstUsed = false;
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        // LogUtil.e("CartVisible");
        if (getUserVisibleHint()) {
            LogUtil.e("MyShuoShuoVisible");
            //如果不是firstvisible才去进行下面的操作  因为第一次很可能出现各种问题
            if (isFirstUsed == false) {
                if(isGetData == false){
                    getOpenNewsKind();
                }


            }
        } else {
            LogUtil.e("faXianFragmentVisible");
        }
    }

    @Override
    public void initData() {

    }

    @Override
    public void assignView(View view) {
        tvGsggMore = (TextView) view.findViewById(R.id.tv_gsgg_more);
        lvGsgg = (ListViewForScrollView) view.findViewById(R.id.lv_gsgg);
        tvZcwjMore = (TextView) view.findViewById(R.id.tv_zcwj_more);
        lvZfwj = (ListViewForScrollView) view.findViewById(R.id.lv_zfwj);
        rgGovYsjs = (RadioGroup) view.findViewById(R.id.rg_gov_ysjs);
        rbGovYs = (RadioButton) view.findViewById(R.id.rb_gov_ys);
        rbGovJs = (RadioButton) view.findViewById(R.id.rb_gov_js);
        tvGovYsjsMore = (TextView) view.findViewById(R.id.tv_gov_ysjs_more);
        vpGovYsjs = (ViewPager) view.findViewById(R.id.vp_gov_ysjs);
        rgDepartYsjs = (RadioGroup) view.findViewById(R.id.rg_depart_ysjs);
        rbDepartYs = (RadioButton) view.findViewById(R.id.rb_depart_ys);
        rbDepartJs = (RadioButton) view.findViewById(R.id.rb_depart_js);
        tvDepartYsjsMore = (TextView) view.findViewById(R.id.tv_depart_ysjs_more);
        vpDepartYsjs = (ViewPager) view.findViewById(R.id.vp_depart_ysjs);



    }

    @Override
    public void initView() {

        RxView.clicks(tvGsggMore)
                .throttleFirst(1000, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        toNewsList(mCommonNewsKind.get(0));
                    }
                });

        RxView.clicks(tvZcwjMore)
                .throttleFirst(1000, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        toNewsList(mCommonNewsKind.get(1));
                    }
                });

        RxView.clicks(tvGovYsjsMore)
                .throttleFirst(1000, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        toNewsList(mNowChooseGovNewsKind);
                    }
                });


        RxView.clicks(tvDepartYsjsMore)
                .throttleFirst(1000, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        toNewsList(mNowChooseDepartNewsKind);
                    }
                });


        mGsggNewsAdapter = new ListAdapterForOpenNews(mGongShiGongGaoNewsList,getActivity());
        mZcwjNewsAdapter = new ListAdapterForOpenNews(mPolicyFileNewsList,getActivity());

        lvGsgg.setAdapter(mGsggNewsAdapter);
        lvGsgg.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent toNewsDetail = new Intent(getActivity(),ActivityNewsDetail.class);
                toNewsDetail.putExtra(IntentKey.INTENT_KEY_NEWS_ID,String.valueOf(mGongShiGongGaoNewsList.get(position).getId()));
                startActivity(toNewsDetail);
            }
        });

        lvZfwj.setAdapter(mZcwjNewsAdapter);
        lvZfwj.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent toNewsDetail = new Intent(getActivity(),ActivityNewsDetail.class);
                toNewsDetail.putExtra(IntentKey.INTENT_KEY_NEWS_ID,String.valueOf(mPolicyFileNewsList.get(position).getId()));
                startActivity(toNewsDetail);
            }
        });


        rgGovYsjs.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId )
                {
                    case R.id.rb_gov_ys :
                        vpGovYsjs.setCurrentItem(0,true);
                        mNowChooseGovNewsKind = mGovYsNewsKind;
                        break;
                    case R.id.rb_gov_js :
                        vpGovYsjs.setCurrentItem(1,true);
                        mNowChooseGovNewsKind = mGovJsNewsKind;
                        break;
                }

            }
        });

        rgDepartYsjs.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId )
                {
                    case R.id.rb_depart_ys :
                        vpDepartYsjs.setCurrentItem(0,true);
                        mNowChooseDepartNewsKind = mDepartYsNewsKind;
                        break;
                    case R.id.rb_depart_js :
                        vpDepartYsjs.setCurrentItem(1,true);
                        mNowChooseDepartNewsKind = mDepartJsNewsKind;
                        break;
                }

            }
        });

        vpGovYsjs.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                switch (position)
                {
                    case 0:
                        rbGovYs.setChecked(true);
                        break;
                    case 1:
                        rbGovJs.setChecked(true);
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


        vpDepartYsjs.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                switch (position)
                {
                    case 0:
                        rbDepartYs.setChecked(true);
                        break;
                    case 1:
                        rbDepartJs.setChecked(true);
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


    }

    @Override
    public void getOpenNewsKind() {
        mPresenter.getOpenNewsKind();
    }

    @Override
    public void onGetOpenNewsKindSuccess(List<NewsKindBean> commonNewsKinds, NewsKindBean govYsNewsKind, NewsKindBean govJsNewsKind, NewsKindBean departYsNewsKind, NewsKindBean departJsNewsKind) {
        mCommonNewsKind.addAll(commonNewsKinds);
        mGovYsNewsKind = govYsNewsKind;
        mGovJsNewsKind = govJsNewsKind;
        mDepartYsNewsKind = departYsNewsKind;
        mDepartJsNewsKind = departJsNewsKind;

        mNowChooseGovNewsKind = mGovYsNewsKind;
        mNowChooseDepartNewsKind = mDepartYsNewsKind;
        //getOpenNewsList(mCommonNewsKind.get());

        getAllNewsList();

    }



    @Override
    public void onGetOpenNewsKindError(String tip) {
        ToastUtil.showShort(getActivity(),tip);
    }

    @Override
    public void getAllNewsList() {
        List<NewsKindBean> newsKindList = new ArrayList<>();

        /*mGovYsNewsKind = govYsNewsKind;
        mGovJsNewsKind = govJsNewsKind;
        mDepaetYsNewsKind = departYsNewsKind;
        mDepaetJsNewsKind = departJsNewsKind;*/

        newsKindList.addAll(mCommonNewsKind);
        newsKindList.add(mGovYsNewsKind);
        newsKindList.add(mGovJsNewsKind);
        newsKindList.add(mDepartYsNewsKind);
        newsKindList.add(mDepartJsNewsKind);

        mPresenter.getAllNewsList(DEFAULT_PAGE_INDEX_STR,DEFAULT_PAGE_PASIZE_STR,newsKindList);
    }

    @Override
    public void onGetAllNewsListSuccess(HashMap<String, List<NewsListBean>> allNewsMap) {
        isGetData = true;

        mGongShiGongGaoNewsList.addAll(allNewsMap.get("公示公告"));
        mPolicyFileNewsList.addAll(allNewsMap.get("政策文件"));
        mGovYsNewsList.addAll(allNewsMap.get("市级政府预算"));
        mGovJsNewsList.addAll(allNewsMap.get("市级政府决算"));
        mDepartYsNewsList.addAll(allNewsMap.get("市级部门预算"));
        mDepartJsNewsList.addAll(allNewsMap.get("市级部门决算"));

        mGsggNewsAdapter.notifyDataSetChanged();
        mZcwjNewsAdapter.notifyDataSetChanged();

        mGovYsJsNewsData.add(mGovYsNewsList);
        mGovYsJsNewsData.add(mGovJsNewsList);

        mDepartYsJsNewsData.add(mDepartYsNewsList);
        mDepartYsJsNewsData.add(mDepartJsNewsList);


        int govYsJsNewsVpHeight = 0;
        if (mGovYsNewsList.size() >= mGovJsNewsList.size())
        {
            govYsJsNewsVpHeight = 40 * mGovYsNewsList.size();
            govYsJsNewsVpHeight +=  (mGovYsNewsList.size() - 1)*5;
        }else {
            govYsJsNewsVpHeight = 40 * mGovJsNewsList.size();
            govYsJsNewsVpHeight +=  (mGovJsNewsList.size() - 1)*5;

        }


        int departYsJsNewsVpHeight = 0;
        if (mDepartYsNewsList.size() >= mDepartJsNewsList.size())
        {
            departYsJsNewsVpHeight = 40 * mDepartYsNewsList.size();
            departYsJsNewsVpHeight +=  (mDepartYsNewsList.size() - 1)*5;
        }else {
            departYsJsNewsVpHeight = 40 * mDepartJsNewsList.size();
            departYsJsNewsVpHeight +=  (mDepartJsNewsList.size() - 1)*5;

        }
        LinearLayout.LayoutParams vpGovYsJsLp = (LinearLayout.LayoutParams) vpGovYsjs.getLayoutParams();
        vpGovYsJsLp.height = DensityUtil.dip2px(getActivity(),govYsJsNewsVpHeight);
        vpGovYsjs.setLayoutParams(vpGovYsJsLp);

        LinearLayout.LayoutParams vpDepartYsJsLp = (LinearLayout.LayoutParams) vpDepartYsjs.getLayoutParams();
        vpDepartYsJsLp.height =  DensityUtil.dip2px(getActivity(),departYsJsNewsVpHeight);;
        vpDepartYsjs.setLayoutParams(vpDepartYsJsLp);



        mGovYsJsNewsVpAdapter = new ViewPagerAdapterOpenNewsYsJs(getActivity(),mGovYsJsNewsData);
        mDepartYsJsNewsVpAdapter = new ViewPagerAdapterOpenNewsYsJs(getActivity(),mDepartYsJsNewsData);

        vpGovYsjs.setAdapter(mGovYsJsNewsVpAdapter);
        vpDepartYsjs.setAdapter(mDepartYsJsNewsVpAdapter);


    }

    @Override
    public void onGetAllNewsListError(String tip) {


    }



    @Override
    public void setPresenter(OpenMainContract.Presenter presenter) {

    }

    @Override
    public void showLoading() {
        showProgressDialog(false,null);
    }

    @Override
    public void dismissLoading() {
        dismissProgressDialog();
    }


    private void toNewsList(NewsKindBean newsKind)
    {
        Intent toNewsList = new Intent(getActivity(), ActivityOpenNewsList.class);
        toNewsList.putExtra(IntentKey.INTENT_KEY_NEWS_KIND,newsKind);
        getActivity().startActivity(toNewsList);

    }
}

